<template>
  <!-- 分包商责任区域设置 -->
  <base-breadcrumb :title="$route.meta.title">
    <!-- 搜索 -->
    <searchData
      :search-data="searchArr"
      @search="search"
    />
    <a-card :bordered="false">
      <!-- <title-name title="分包商责任区域设置" /> -->
      <a-row :gutter="10">
        <!-- 侧边栏 -->
        <a-col
          :span="4"
          style="border-right: 1px solid #d9d9d9"
        >
          <!-- 树搜索 -->
          <tree-district
            :id="id"
            ref="treeSearch"
            showEnabledButton
            :show-button="false"
            :initExpandAll="false"
            :showSubcontrctorBtn="true"
            :selected-keys.sync="selectedKeys"
            :select-options.sync="selectOptions"
            is-all
            @loader="search"
          >
            <!-- 若已测量则标记 -->
            <template
              slot-scope="{ data }"
              slot="after"
            >
              <a-tooltip v-if="data.isMapping">
                <template slot="title">已测量</template>
                <a-icon
                  type="check-circle"
                  style="margin: 4px; color: #00ac5a"
                />
              </a-tooltip>
              <a-tooltip v-if="!data.hasChildren">
                <template slot="title">{{ `${data.bimNumber > 0 ? '已' : '未'}关联${data.bimNumber > 0 ? data.bimNumber + '个' : ''}BIM模型` }}</template>
                <a-badge
                  :numberStyle="{ fontSize: '10px', padding: '0 2px' }"
                  :count="data.bimNumber"
                  :overflow-count="9"
                >
                  <a-icon
                    @click.stop="handleRelease(data)"
                    type="link"
                    style="margin: 4px"
                    :style="{ color: data.bimNumber > 0 ? '#1890ff' : '#ccc' }"
                  />
                </a-badge>
              </a-tooltip>
            </template>
          </tree-district>
          <!-- :addDisable="addDisable && (pic ? true : false)" -->
        </a-col>
        <!-- 主内容 -->
        <a-col :span="20">
          <!-- 上传施工图 -->
          <a-row
            type="flex"
            class="mb12"
            justify="space-between"
            style="width: 100%"
          >
            <a-row type="flex">
              <upload-list
                business-code="PM04"
                upload-type="normal"
                class="btn_right"
                custom-btn
                :count="1"
                :isReplace="true"
                :multiple="false"
                @fileArrysData="handleUpload"
                v-if="hideBuquBtn()"
              >
                <a-button
                  :disabled="!selectOptions || !selectOptions.parentId"
                  v-btnPermission="'qm_029_add_01'"
                  :loading="uploading"
                  type="primary"
                  :icon="pic ? 'reload' : 'upload'"
                >
                  {{ pic ? '重新上传施工图' : '添加施工图' }}
                </a-button>
              </upload-list>
              <a-button
                v-btnPermission="'qm_029_add_02'"
                :disabled="!pic || !selectOptions || !selectOptions.parentId"
                class="btn_right"
                type="primary"
                icon="plus"
                @click="handleManage(0)"
                v-if="hideBuquBtn()"
              > 添加责任区域 </a-button>
              <a-button
                v-if="type != 1&&hideBuquBtn()"
                :disabled="!selectOptions || !selectOptions.parentId"
                v-btnPermission="'qm_029_inh_10'"
                class="btn_right"
                type="primary"
                icon="copy"
                @click="visibleInherit = true"
              >
                继承
              </a-button>
              <!-- 当type不是1（安检）显示按钮，当前节点选中且没有子级且不是根节点可操作 -->
              <a-button
                v-if="type != 1&&hideBuquBtn()"
                :disabled="!selectOptions || selectOptions.hasChildren || !selectOptions.parentId"
                type="primary"
                icon="link"
                @click="
                  extraParams.subAreaId && delete extraParams.subAreaId
                  visibleBim = true
                "
              >
                关联BIM模型
              </a-button>
            </a-row>
            <a-button
              type="primary"
              icon="arrow-left"
              @click="$multiTab.close()"
            > 返回</a-button>
          </a-row>
          <!-- 施工图 -->
          <a-spin
            :spinning="spinning"
            class="mb12"
            align="center"
          >
            <pre-view
              :preview-image="pic"
              :visible.sync="preVisible"
            />
            <!-- 图片加载错误 -->
            <a-result
              v-if="isError"
              status="404"
              title="图片加载失败"
            ></a-result>
            <!-- 施工图 -->
            <template v-else>
              <img
                v-if="pic"
                :src="pic"
                alt="施工图"
                style="max-height: 500px; max-width: 100%; cursor: pointer"
                @click.stop="preVisible = true"
              />
              <empty
                v-else
                description="暂未上传施工图"
              />
            </template>
          </a-spin>
          <!-- 表格 -->
          <list-table
            ref="table"
            table-layout="fixed"
            size="default"
            :scroll="{ x: 1500 }"
            row-key="id"
            :columns="columns"
            :request="loadData"
            :alert="true"
            show-size-changer
            show-quick-jumper
            show-pagination="auto"
          >
            <!-- 表格操作栏 -->
            <span
              slot="action"
              slot-scope="text, record"
            >
              <MoreButton>
                <a
                  v-btnPermission="'qm_029_loo_05'"
                  @click="handleManage(2, record)"
                >查看</a>
                <a
                  v-btnPermission="'qm_029_edi_03'"
                  @click="handleManage(1, record)"
                >编辑</a>
                <a
                  v-btnPermission="'qm_029_del_04'"
                  @click="handleRemoveNode(record)"
                >移除</a>
              </MoreButton>
            </span>
          </list-table>
        </a-col>
      </a-row>
    </a-card>
    <!-- 责任区域表单弹窗 -->
    <DialogDistrict
      ref="dialogDistrict"
      :moduleType="type"
      :visible.sync="visible"
      :edit-model="editModel"
      :form="form"
      :header-title="headerTitle"
      :isMandatory="true"
      @confirm="submitForm"
    />
    <!-- 继承表单弹窗 -->
    <DialogInherit
      ref="dialogInherit"
      :visible.sync="visibleInherit"
      :form="form"
      @confirm="handleInherit"
    />
    <!-- BIM模型列表弹窗 -->
    <BimView
      ref="bimView"
      :visible.sync="visibleBim"
      :zIndex="949"
      :extraParams="extraParams"
      @handleOpen="handleOpen"
    />
    <!-- 关联BIM模型弹窗 -->
    <BimRelease
      ref="bimRelease"
      :zIndex="950"
      :destroyOnClose="true"
      :isRelease="!extraParams.subAreaId"
      :visible.sync="visibleRelease"
      :modelList="modelList"
      @confirm="handleBim"
    />
  </base-breadcrumb>
</template>

<script>
import DialogDistrict from '@/views/quality/currency/subcontractorsDistrictSetting/dialogDistrict.vue' // 责任区域表单弹窗
import DialogInherit from '@/views/quality/currency/subcontractorsDistrictSetting/dialogInherit.vue' // 继承表单弹窗
import uploadList from '@/components/UploadList' // 上传文件
import PreView from '@/components/PreView' // 图片预览
import TreeDistrict from '@/components/businessComponents/TreeDistrict' // 树
import { Empty } from 'ant-design-vue' // 无数据提示
import { set, setImage, setSubItem, inherit } from '@/api/quality/currency' // api
import { associateBimModel, getList } from '@/api/bimIntegrate/bimModel' // api
import cloneDeep from 'lodash.clonedeep' // 深拷贝
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import Vue from 'vue'
import BimView from '@/components/Dialog/BimView' // BIM模型关联列表
import BimRelease from '@/components/Dialog/BimRelease' // BIM模型关联

const searchArr = [
  // 搜索框
  {
    name: '整改人',
    value: 'rectifierPeople',
    type: 'input'
  },
  {
    name: '责任人',
    value: 'dutyPeople',
    type: 'input'
  }
]
const columns = [
  {
    title: '整改人',
    dataIndex: 'rectificationPeople',
    width: 230,
    ellipsis: true,
    customRender(text, record, index) {
      // console.log(record)
      // console.log(window.location)
      if (record.safeRectifierValue) {
        return Object.values(record.safeRectifierValue).join('，')
      }
      return record.rectificationPeople
    }
  },
  {
    title: '责任分包商',
    dataIndex: 'dutySubcontractor',
    ellipsis: true
    // width: 130,
  },
  {
    title: '责任人',
    dataIndex: 'dutyPeople',
    ellipsis: true
    // width: 130,
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100,
    customRender(record) {
      return record == 0 ? '停用' : '启用'
    }
  },
  {
    title: '责任区域描述',
    dataIndex: 'dutyAreaDescription',
    ellipsis: true
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 230,
    fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    Empty,
    PreView,
    DialogDistrict,
    DialogInherit,
    uploadList,
    TreeDistrict,
    BimView,
    BimRelease
  },
  watch: {
    '$route.fullPath'() {
      this.init()
    }
  },
  mounted() {
    this.init()
  },
  computed: {
    // 树节点api
    api() {
      return setSubItem
    },
    // 弹窗动态标题
    headerTitle() {
      return ['添加责任区域', '编辑责任区域', '查看责任区域'][this.editModel]
    },
    // 表格列表请求参数
    args() {
      let args = this.queryParam
      // 添加分部分项id
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        args.subItemId = this.selectedKeys[0]
      }
      return args
    },
    // 查看关联BIM模型列表请求参数
    extraParams() {
      return { projectId: this.id }
    }
  },
  data() {
    this.columns = columns
    this.searchArr = searchArr
    return {
      isError: false, // 图片是否加载错误
      spinning: false, // 图片加载控件
      preVisible: false, // 图片预览
      uploading: false, // 上传加载框
      token: '',
      editModel: 0, // 操作类型：0 添加 1 编辑 3 查看
      visible: false, // 责任区域弹窗控件
      visibleTwo: false, // 节点弹窗控件
      visibleInherit: false, // 继承弹窗控件
      visibleBim: false, // BIM模型列表弹窗控件
      visibleRelease: false, // BIM模型关联弹窗控件
      modelList: [], // BIM模型列表
      form: {}, // 弹窗参数
      pic: '', // 施工图
      queryParam: {}, // 查询参数
      loadData: (parameter) => {
        let that = this
        if (!that.selectedKeys.length) {
          return false
        }
        const requestParameters = Object.assign({}, parameter, that.args)
        that.spinning = true
        return set
          .list(requestParameters)
          .then((res) => {
            // 深拷贝回调对象
            that.spinning = false
            let datas = cloneDeep(res)
            datas.data =
              res.data.listDutyArea && res.data.listDutyArea.length > 0
                ? res.data.listDutyArea.map((item) => {
                    // 格式化整改人
                    item.rectificationPeople = item.rectificationPeople?.length > 0 ? item.rectificationPeople.join('，') : ''
                    // 格式化责任人
                    item.dutyPeople = item.dutyPeople?.length > 0 ? item.dutyPeople.join('，') : ''
                    return item
                  })
                : [] // 列表对象
            // 映射施工图
            if (res.data.fileInfo) {
              let img = new Image()
              img.src = '/api/ycloud-file-center/oper/download?access_token=' + that.token + '&fileId=' + res.data.fileInfo.fileId
              img.onload = function (e) {
                that.isError = false
                // 施工图
                that.pic = img.src
              }
              img.onerror = (e) => {
                that.isError = true
              }
            } else {
              that.addDisable = false
            }
            return datas
          })
          .catch((res) => {
            that.spinning = false
          })
      }, // 加载数据方法 必须为 Promise 对象
      //   tableHeight: 500, // 表格高度
      selectOptions: {}, // 树选中节点对象
      selectedKeys: [], // 树选中节点
      addDisable: false // 添加节点按钮禁用状态
    }
  },
  methods: {
    /**
     * @description: 初始化
     */
    init() {
      let that = this
      that.type = that.$route.query.type
      that.$nextTick(() => {
        that.token = Vue.getAcloudProvider().getAccessToken()
        // 获取分项工程
        that.$refs.treeSearch.getList().then((res) => {
          that.search()
        })
      })
    },
    // 上传施工图
    handleUpload(e) {
      console.log(e)
      let that = this
      that.uploading = true
      setImage
        .create({
          businessCode: 'PM04',
          businessId: that.selectedKeys[0],
          fileInfo: e[e.length - 1]
        })
        .then((res) => {
          that.uploading = false
          // if (res.code == 200) {
          that.pic = ''
          that.$message.success('上传成功！')
          that.$nextTick(() => {
            that.search()
          })
          // } else {
          //   // that.$message.warning('上传失败！')
          // }
        })
        .catch((res) => {
          that.uploading = false
        })
    },
    // 头部搜索
    search(value) {
      // 赋值表单
      if (value) {
        this.queryParam = value
      }
      this.pic = ''
      this.addDisable = true
      this.$refs.table.refresh(true)
    },
    /**
     * @description: 继承
     * @param {*} e：表单
     */
    handleInherit(e) {
      let that = this
      // 提交区域表单
      inherit
        .create(e)
        .then((res) => {
          that.$refs.dialogInherit.loading = false
          if (res.code == 200 || res.data.code == 200) {
            that.$message.success('继承成功！')
            that.visibleInherit = false // 关闭弹窗
            that.search()
          }
        })
        .catch(() => {
          that.$refs.dialogInherit.loading = false
        })
    },
    // 提交表单
    submitForm(e) {
      let that = this
      let name = ['create', 'update'][that.editModel] // 根据操作切换url地址
      // 提交区域表单
      set[name](e)
        .then((res) => {
          that.$refs.dialogDistrict.loading = false
          if (res.code == 200 || res.data.code == 200) {
            that.$message.success(['添加', '编辑'][that.editModel] + '成功！')
            that.visible = false // 关闭弹窗
            that.search()
            // } else {
            //   that.$message.warning(['添加', '编辑'][that.editModel] + '失败！')
          }
        })
        .catch((res) => {
          that.$refs.dialogDistrict.loading = false
        })
    },
    // 移除区域
    handleRemoveNode(e) {
      let that = this
      that.$confirm({
        title: '温馨提示',
        content: '确认移除？',
        okText: '提交',
        cancelText: '关闭',
        onOk() {
          return set.remove({ id: e.id }).then((res) => {
            // if (res.data.code == 200) {
            that.$message.success('移除成功！')
            that.search()
            // } else {
            //   that.$message.warning('移除失败！')
            // }
          })
        }
      })
    },
    // 业务区域：新增/编辑/查看
    handleManage(b, a) {
      this.editModel = b
      // b 操作类型;a 行数据
      this.form = b ? Object.assign({}, a, { projectId: this.id, branchCompanyId: this.branchCompanyId }) : { status: '1', projectId: this.id, subItemId: this.selectOptions.id, branchCompanyId: this.branchCompanyId }
      this.visible = true // 打开弹窗
    },
    /**
     * @description: 打开模型列表
     * @param {Object} data：节点数据
     */
    handleRelease(data) {
      if (data.bimNumber > 0) {
        this.extraParams.subAreaId = data.id
        // 关联数量大于1则打开模型列表，只有一个时则直接打开模型详情
        if (data.bimNumber > 1) {
          this.visibleBim = true
        } else {
          let args = { pageSize: 10, pageNum: 1, param: { projectId: this.id, subAreaId: data.id } }
          data.loading = true
          // 请求模型参数
          getList(args)
            .then((res) => {
              if (res.code === '0') {
                const record = res.data?.list?.[0]
                const params = [{ id: record.id, modelId: record.modelFileId, version: record.modelFileVersion, modelTitle: record.modelName }]
                this.handleOpen(params)
              }
            })
            .finally(() => {
              data.loading = false
            })
        }
      }
    },
    /**
     * @description: 打开模型
     * @param {Array} data：模型列表或者模型选中项
     */
    handleOpen(data) {
      this.modelList = data
      console.log(this.modelList,2222)
      this.visibleBim = false
      this.visibleRelease = true
    },
    /**
     * @description: BIM模型关联
     * @param {Array<Number>} floorIdList：关联楼层列表
     */
    handleBim(floorIdList, floorIdUuidList) {
      this.$confirm({
        title: '提示',
        content: '确定要关联BIM模型吗？',
        onOk: () => {
          const args = {
            floorIdList,
            floorIdUuidList,
            modelId: this.modelList[0].id,
            subAreaId: this.selectedKeys[0]
          } // 关联参数
          return associateBimModel(args).then((res) => {
            if (res.code == 0 || res.data.code == 0) {
              this.$message.success('关联成功！')
              this.visibleRelease = false
              this.$refs.treeSearch?.getList()
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-tree li .ant-tree-node-content-wrapper {
  white-space: pre-wrap;
  height: auto;
  width: calc(100% - 24px);
}
</style>